import flask,json,requests,re
from flask import request,render_template,make_response
from flask_bilibili.app import models
from flask_sqlalchemy import SQLAlchemy
from app.models import User,Video

server = flask.Flask(__name__)


@server.route('/index',methods=['get','post'])
def index():
    return render_template('index.html')

@server.route('/user',methods=['get','post'])
def user_info():
    # 实例化模型
    obj = User.query.filter().limit(50)
    content={'obj':obj}
    return render_template('user_info.html',content=content)
@server.route('/video',methods=['get','post'])
def video_info():
    obj_video = Video.query.filter().limit(50)
    content = {'obj_video':obj_video}
    return render_template('video_info.html', content=content)

@server.route('/find/<aid>',methods=['get','post'])
def reg(aid):
    dict = {}
    aid = aid
    headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36',
            'Host': 'api.bilibili.com',
        }
    url = 'https://api.bilibili.com/x/web-interface/view?aid={}'.format(aid)

    r = requests.get(url,headers=headers,verify=False)

    cid_json=r.content.decode('utf-8')
    cid_list=json.loads(cid_json)
    cid = cid_list.get('data','').get('cid','')

    # 判断是否有cid
    if cid:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36',
            'Host': 'comment.bilibili.com',
        }
        cid_url = 'http://comment.bilibili.com/{}.xml'.format(cid)
        comment = requests.get(cid_url,headers = headers)
        # 得到json数据
        respone_html = comment.content.decode('utf-8')
        # 转为字典格式
        danma = re.compile(r'<d p=.+?>(.+?)</d>').findall(respone_html)
        if danma == []:
            dict['aid'] = aid
            dict['danma'] = '抱歉,此视频没有弹幕'
            return json.dumps(dict,ensure_ascii=False)
        else:
            dict['aid'] = aid
            dict['danma'] = danma
            return json.dumps(dict,ensure_ascii=False)

if __name__ == '__main__':
    server.run(port=8889,debug=True,host='127.0.0.1')





